var ws_protocol = 'ws'; // ws 或 wss
var ip = '47.114.174.24'
var port = 9326

var heartbeatTimeout = 5000; // 心跳超时时间，单位：毫秒
var reconnInterval = 1000; // 重连间隔时间，单位：毫秒

var url = 'http://backend.dongfangqianmen.com'
var binaryType = 'blob'; // 'blob' or 'arraybuffer';//arraybuffer是字节
var handler = new IMHandler()
var myself = 0;
var mtime = "";
var myname = "";
var merchantname = "";
var merchantimg = "";
var myimg = "";
var group_id = "";
var merchantId = "";
var myid = "";
var type = "";


var tiows


//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}

$('.content').css('height',$('body').height() - 70);

function initWs() {
    if (tiows != null){
        tiows.close();
    }

    // 获取from_id 和from_type
    var from_id = getQueryVariable('from_id');  // 发送人ID
    var from_type = getQueryVariable('from_type'); // 发送人
    type = getQueryVariable('type');
    group_id = group_id || getQueryVariable('group_id');

    let data = {};
    data.type = type;
    data.userId = myid || group_id.split('-')[0];
    data.merchantId = merchantId || group_id.split('-')[1];
    data.endTime = Date.parse(new Date())/1000;
    data.startTime = Date.parse(new Date())/1000 - 7* 24*60*60;
    $.ajax({
        url: url + "/api/tiny-shop/v1/chat/chat-kefu/chat-kefu",
        type:'POST',
        async: false,
        data: data,
        success:function(res){
            console.log(res)
            var ico,imgcls,spancls,ncikcls,msgName;
            var content = document.getElementsByTagName('ul')[0];

            if (type == 'merchant'){
                merchantname = res.data.user.realname+'-'+res.data.user.id
                merchantimg = res.data.user.head_portrait
                myimg = res.data.merchant.logo
                myname = res.data.merchant.title
                myid = res.data.user.id
                merchantId = res.data.merchant.id
            }else{
                myname = res.data.user.realname+'-'+res.data.user.id
                merchantId = res.data.merchant.id
                myid = res.data.user.id
                myimg = res.data.user.head_portrait
                merchantimg = res.data.merchant.logo
                merchantname = res.data.merchant.title
            }
            content.innerHTML = '';
            for (let i=0; i<res.data.data.length;i++){
                if (res.data.data[i].to_type == (type == 'merchant'?'0':'1')){
                    ico=myimg;
                    imgcls="imgright";
                    spancls="spanright";
                    nickcls="nickright";
                    msgName=myname.split('-')[0]
                }else{
                    ico=merchantimg;
                    imgcls="imgleft";
                    spancls="spanleft";
                    nickcls="nickleft"
                    msgName=merchantname.split('-')[0]
                }
				if(res.data.data[i].type == '1'){
					content.innerHTML += '<li><img src="'+ico+'" class="'+imgcls+'"><span class="'+nickcls+'">'+msgName+'</span><span class="'+spancls+'">'+res.data.data[i].content+'</span></li>';
				}else{
					content.innerHTML += '<li><img src="'+ico+'" class="'+imgcls+'"><span class="'+nickcls+'">'+msgName+'</span><span class="'+spancls+' spanimg"><img src="'+res.data.data[i].content+'" alt="" class="img-box"></span></li>';
				}
            }
            content.scrollTop=content.scrollHeight;
            setTimeout(function () {
                content.scrollTop=content.scrollHeight;
            },1000)
            // myname = res.data[0].merchant
        },
        error:function(){
           alert('接口错误')
        }
    });


    var queryString =  'name='+myname + '&from_id=' + from_id + '&from_type=' + from_type + '&group_id=' + group_id;

    var param = "";
    tiows = new tio.ws(ws_protocol, ip, port, queryString, param, handler, heartbeatTimeout, reconnInterval, binaryType)
    tiows.connect()
}

//回车事件绑定
document.onkeydown = function (e) {
    var ev = document.all ? window.event : e;
    if (ev.keyCode == 13) {
        event.cancelBubble=true;
        event.preventDefault();
        event.stopPropagation();
        sendMsg(1);
    }
}

function sendMsg(types,value) {
    var msg = '',to_type='1';
    if (types==1){
        msg = document.getElementById('messageText').value;
        msg = msg.replace(/\ +/g,"");
        msg = msg.replace(/[\r\n]/g,"");
    }else {
        msg = value;
    }
    if (type == 'merchant'){
        to_type = '0'
    }
    if (msg==''){
        document.getElementById('messageText').value = "";
        document.getElementById('messageText').textContent = "";
        return;
    }
    if (msg=='' || myid=='' || merchantId == '' || types ==='' || to_type==''){
        alert('数据格式出错')
        return
    }
    var content = {
        'group_id': group_id,
        'message' : msg,
        from_id: myid,
        to_id: merchantId,
        type:types,
        to_type:to_type,
    }
    console.log(content)
    tiows.send(JSON.stringify(content));
    document.getElementById('messageText').value = "";
}

function clearMsg() {
    document.getElementById('contentId').innerHTML = ''
}


function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate() ) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes() ;
    return M + D + h + m ;
}
/***
 * 获取地址栏的信息
 * @param variable
 * @returns {string|boolean}
 */
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

function fileupload(file) {
    var formData = new FormData();
    formData.append("file", file.files[0]);
    $.ajax({
        url: url + '/api/merchants/file/images',
        type: 'post',
        data: formData,
        processData: false,
        contentType: false,
        success: function (res) {
            if (res.code == 200){
                sendMsg(0,res.data.url)
            }

        }
    });

}
function initPc() {
    var from_id = getQueryVariable('from_id');  // 发送人ID
    var urlId = getQueryVariable('group_id').split('-')[1]||'';
    let data = {
        userId: from_id
    }
    if(getQueryVariable('type') == 'merchant'){
        data = {
            merchantId: from_id
        }
        $.ajax({
            url: url + '/api/tiny-shop/v1/chat/chat-kefu/message-list',
            type: 'post',
            async: false,
            data: data,
            success: function (res) {
                console.log(res)
                if (res.code == 200) {
                    for (let i=0;i<res.data.length;i++){
                        let active = '';
                        if (i==0){
                            active = 'active'
                        }
                        $('#msgList').append('<div class="left-box '+active+'" onclick="activeMerchant('+res.data[i].member.id+',this)">' +
                            '<div class="img"><img src="'+res.data[i].member.head_portrait+'" alt=""></div>' +
                            '<div class="conter">' +
                            '<span class="name">'+res.data[i].member.realname+'</span>' +
                            '<span class="time">'+timestampToTime(res.data[i].updated_at)+'</span>' +
                            '<span class="conter1" >'+((+res.data[i].type==1)?res.data[i].content:'[图片]')+'</span>' +
                            '</div>' +
                            '</div>')
                    }
                    if (res.data.length !=0){
                        group_id = res.data[0].member.id+'-'+from_id
                        initWs(1);
                    }

                } else {
                    alert(res.message);
                }
            }
        });
    }else{
        $.ajax({
            url: url + '/api/tiny-shop/v1/chat/chat-kefu/message-list',
            type: 'post',
            async: false,
            data: data,
            success: function (res) {
                let data = {} , info = {};
                if (res.code == 200) {
                    if (res.data.length == 0 && !urlId){
                        return
                    }else if(res.data.length != 0 && !urlId ){
                        merchantId = res.data[0].merchant.id;
                    }
                    data = res.data;
                    console.log(data)
                    for (let i=0;i<res.data.length;i++){
                        if ( res.data[i].merchant.id == urlId){
                            merchantId = res.data[i].merchant.id;
                        }
                    }
                    if (merchantId == '' && urlId){
                        let params = {
                            merchant_id: urlId ,
                            page: 1
                        }
                        $.ajax({
                            url: url + '/api/tiny-shop/v1/merchant/merchant/info',
                            type: 'post',
                            data: params,
                            success: function (res) {
                                if (res.code == 200){
                                    console.log(res)
                                    $('#msgList').append('<div class="left-box active">' +
                                        '<div class="img"><img src="'+res.data.logo+'" alt=""></div>' +
                                        '<div class="conter">' +
                                        '<span class="name">'+res.data.title+'</span>' +
                                        '<span class="conter1">欢迎咨询</span>' +
                                        '</div>' +
                                        '</div>')

                                    for (let i=0;i<data.length;i++){
                                        $('#msgList').append('<div class="left-box" onclick="activeMerchant('+data[i].merchant.id+')">' +
                                            '<div class="img"><img src="'+data[i].merchant.logo+'" alt=""></div>' +
                                            '<div class="conter">' +
                                            '<span class="name">'+data[i].merchant.title+'</span>' +
                                            '<span class="time">'+timestampToTime(data[i].updated_at)+'</span>' +
                                            '<span class="conter1">'+data[i].content+'</span>' +
                                            '</div>' +
                                            '</div>')
                                    }
                                }else{
                                    alert(res.message);
                                }
                            }
                        });
                    }else{
                        for (let i=0;i<data.length;i++){
                            let active = ''
                            if (data[i].merchant.id == merchantId){
                                active = 'active'
                            }
                            $('#msgList').append('<div class="left-box '+active+'" onclick="activeMerchant('+data[i].merchant.id+',this)">' +
                                '<div class="img"><img src="'+data[i].merchant.logo+'" alt=""></div>' +
                                '<div class="conter">' +
                                '<span class="name">'+data[i].merchant.title+'</span>' +
                                '<span class="time">'+timestampToTime(data[i].updated_at)+'</span>' +
                                '<span class="conter1">'+data[i].content+'</span>' +
                                '</div>' +
                                '</div>')
                        }
                    }
                    initWs(1);
                } else {
                    alert(res.message);
                }
            }
        });
    }

}
function activeMerchant(id,that) {
    $('.left-box').removeClass('active')

    $(that).addClass('active')
    if(getQueryVariable('type') == 'merchant' && myid != id){
        group_id = id+'-'+merchantId
        myid = id;
        initWs();
    }else if (getQueryVariable('type') != 'merchantId' && merchantId != id){
        group_id = myid+'-'+id
        merchantId = id;
        initWs();
    }

}
if (isPc){
    initPc()
}else {
    initWs(1);
}

// setInterval(showTime, 1000);